package com.jintoufs.util.resource;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/7/18,018.
 */
public class ResourceNodeTree {
    /**
     * 树根
     */
    private ResourceTreeNode root;


    private List<Object> fristList;

    /**
     * 构造函数
     */
    public ResourceNodeTree() {
        root = new ResourceTreeNode(new Node(0));
        fristList = new ArrayList<>();
    }

    /**
     * 生成一颗多叉树，根节点为root
     * R
     *
     * @param treeNodes 生成多叉树的节点集合
     * @return ResourceNodeTree
     */
    public ResourceNodeTree createTree(List<Node> treeNodes) {
        if (treeNodes == null) {
            return null;
        }

        ResourceNodeTree ResourceNodeTree = new ResourceNodeTree();

        //将所有节点添加到多叉树中
        for (Node treeNode : treeNodes) {
            if (treeNode.getParentId() == 0) {
                //向根添加一个节点
                ResourceNodeTree.getRoot().getChildList().add(new ResourceTreeNode(treeNode));
            } else {
                addChild(ResourceNodeTree.getRoot(), treeNode);
            }
        }

        return ResourceNodeTree;
    }

    /**
     * 向指定多叉树节点添加子节点
     *
     * @param ResourceNodeTree 多叉树节点
     * @param child            节点
     */
    public void addChild(ResourceTreeNode ResourceNodeTree, Node child) {
        for (ResourceTreeNode item : ResourceNodeTree.getChildList()) {
            if (item.getData().getNodeId() == child.getParentId()) {
                //找到对应的父亲
                item.getChildList().add(new ResourceTreeNode(child));
                break;
            } else {
                if (item.getChildList() != null && item.getChildList().size() > 0) {
                    addChild(item, child);
                }
            }
        }
    }

    public void firstOrder(ResourceTreeNode root) {
        fristList.add(root.getData().getText());
        if (root.getChildList().size() > 0) {
            for (ResourceTreeNode treeNode : root.getChildList()) {
                firstOrder(treeNode);
            }
        }
    }

    public ResourceTreeNode getRoot() {
        return this.root;
    }

    public void setRoot(ResourceTreeNode root) {
        this.root = root;
    }

    public List<Object> getFristList() {
        return this.fristList;
    }

    public void setFristList(List<Object> fristList) {
        this.fristList = fristList;
    }

}
